package com.ujiuye.web;

import com.ujiuye.enity.Student;
import com.ujiuye.service.StuService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet("/updateStu")
public class UpdateServlet extends HttpServlet {
    //开始修改学生信息
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        //获取id
        String sid = req.getParameter("sid");
        Student s = new Student();
        Map<String, String[]> map = req.getParameterMap();
        //获取文件域对象
        Part p = req.getPart("npic");
        //获取上传新头像的名字
        String fileName = p.getSubmittedFileName();
        String path = "d:/pic";//存储头像的文件路径
        //map信息映射到s
        try {
            BeanUtils.populate(s, map);
            //如果上传了新头像
            if (!"".equals(fileName)) {
                //空表示没有上传,非空就是上传了新头像
                //然后重命名
                fileName = UUID.randomUUID() + fileName;
                s.setSpic(fileName);
                //上传新头像
                p.write(path + File.separator + fileName);
                //删除旧头像
                File f = new File(path + File.separator + map.get("spic")[0]);
                f.delete();
            }
            //进行修改
            StuService ss = new StuService();
            boolean b = ss.upStu(s);
            if (b) {
                //修改成功 展示修改的信息
                req.getRequestDispatcher("/show").forward(req, resp);
            } else {
                pw.println("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
